#!/bin/env ruby

# (c) Oleg Puchinin March 2012

class Compiler

	def initialize
		@cxx = "/usr/bin/g++"
		@includes = "-I../gclib/include -Iinclude -I../include " 
		@debug = :false
	end

	def clean_in_dir dir_name		
		old_dir = Dir.pwd
		Dir.chdir dir_name
		Dir["src/*.o"].each { |one|
			File.unlink one
		}
		Dir.chdir old_dir
	end

	def find_objects_in_source_dir
		obj_list = Dir["src/*.o"]
		obj_list = obj_list.join " "
		obj_list
	end

	def file_must_be_compiled src,obj
		return true	#FIXME

		mtime1 = File.stat(src).mtime  
		begin
			st2 = File.stat(obj)
		rescue Errno::ENOENT
			return true
		end
		mtime1 > st2.mtime
	end


	def compile_program_or_library_in_dir dir_name, fpic = ""
		old_dir = Dir.pwd
		Dir.chdir dir_name
		sources = Dir["src/*.cxx"]
		if @debug == :false
			cxxflags = "-c -m64 -Wall -O3 #{fpic}" 
		else
			cxxflags = "-c -m64 -Wall -g3 #{fpic}"	
		end

		sources.each { |one|
			obj = one.dup
			obj[/\.cxx/] = ".o"
			next if not file_must_be_compiled one,obj

			cmd = "#{@cxx} #{cxxflags} #{@includes} #{one} -o #{obj}"
			print "#{@cxx} #{cxxflags} #{@includes} #{dir_name}/#{one} -o #{obj}" + "\n"
			system cmd			
			if $?.exitstatus > 0 
				exit $?.exitstatus
			end
		}
		Dir.chdir old_dir
	end

	def link_library_in_dir dir_name, lib_name
		old_dir = Dir.pwd
		Dir.chdir dir_name	

		obj_list = Dir["src/*.o"]
		obj_list = obj_list.join " "
		print "g++ -shared #{obj_list} -o #{lib_name}\n"
		system "g++ -shared #{obj_list} -o #{lib_name}"
		if $? == 0 
			#print "LINKED OK\n"
		else 
			#print "LINKED FAIL\n"
		end
		Dir.chdir old_dir
	end

	def link_program_in_dir dir_name, libs
		old_dir = Dir.pwd
		Dir.chdir dir_name
			
		obj_list = find_objects_in_source_dir
		print "g++ #{libs} #{obj_list} -o #{dir_name}\n"		
		system "g++ #{libs} #{obj_list} -o #{dir_name}"

		if $? == 0 
			print "LINKED OK\n"
		else 
			print "LINKED FAIL\n"
		end

		Dir.chdir old_dir		
	end
end

c = Compiler.new

if ARGV[0] == "clean" 
	c.clean_in_dir "gclib"
	c.clean_in_dir "sblib"
	c.clean_in_dir "silentbob"
else
#	print "COMPILING GCLIB\n"
	c.compile_program_or_library_in_dir "gclib", "-fPIC"
	c.link_library_in_dir "gclib", "libgclib.so"
#	puts
#	puts
#	print "COMPILING SBLIB\n"
	c.compile_program_or_library_in_dir "sblib", "-fPIC"
	c.link_library_in_dir "sblib", "libsblib.so"
#	puts 
#	puts
#	print "COMPILING BOB\n"
	c.compile_program_or_library_in_dir "silentbob" 
	c.link_program_in_dir "silentbob", "-L../gclib -L../sblib -lgclib -lsblib"
end

